package pos.data;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import com.csvreader.CsvWriter;

import pos.domain.Detail;
import pos.domain.Product;
import pos.utils.UIDGenerator;

public class CSVDetailDAO implements IDetailDAO {
    
	   IProductDAO pdao;
	    
	    public CSVDetailDAO() {
	        pdao = new CSVProductDAO();
	    }

	
	private CsvWriter openFile() {

		CsvWriter csvOutput = null;
		String outputFile = "data/details.csv";

		// before we open the file check to see if it already exists
		boolean alreadyExists = new File(outputFile).exists();

		try {
			// use FileWriter constructor that specifies open for appending
			csvOutput = new CsvWriter(new FileWriter(outputFile, true), ',');

			// if the file didn't already exist then we need to write out the
			// header line
			if (!alreadyExists) {
				csvOutput.write("OID");
				csvOutput.write("orderOID");
				csvOutput.write("productOID");
				csvOutput.write("note");
				csvOutput.write("quantity");
				csvOutput.endRecord();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

		return csvOutput;

	}

	private void closeFile(CsvWriter writer) {
		writer.close();

	}

	public void delete(String orderOID) {
    	//TODO
    }

    public void insert(List details, String orderOID) {

    	CsvWriter writer = this.openFile();

    	for (Iterator it = details.iterator(); it.hasNext();) {
    		Detail d = (Detail) it.next();

    		try {
				writer.write(UIDGenerator.getInstance().getKey());
				writer.write(orderOID);
				String oidp = pdao.selectProductOID(d.getProduct().getProductID());
				writer.write(oidp);
				writer.write(d.getNote());
				writer.write(String.valueOf(d.getQuantity()));
				writer.endRecord();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	closeFile(writer);
    }

    public List select(String orderOID) {
        return null;
    }

    }


